package my.mall.common.bean

import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import my.mall.common.exception.JsonParseException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class JsonParser(
    private val objectMapper: ObjectMapper
) {

    fun <T> parseJsonToObj(jsonStr: String?, clazz: Class<T>?): T {
        return try {
            objectMapper.readerFor(clazz).readValue(jsonStr)
        } catch (e: JsonProcessingException) {
            throw JsonParseException(jsonStr, e)
        }
    }

    fun <T> parseJsonToList(jsonStr: String?, clazz: Class<T>?): List<T> {
        return try {
            objectMapper.readerForListOf(clazz).readValue(jsonStr)
        } catch (e: JsonProcessingException) {
            throw JsonParseException(jsonStr, e)
        }
    }

    fun parseJsonToJsonNode(jsonStr: String?): JsonNode {
        return try {
            objectMapper.readTree(jsonStr)
        } catch (e: JsonProcessingException) {
            throw JsonParseException(jsonStr, e)
        }
    }

    fun formatObjToJson(obj: Any?): String {
        return try {
            objectMapper.writeValueAsString(obj)
        } catch (e: JsonProcessingException) {
            throw JsonParseException(e)
        }
    }
}
